package io.bluefw.blueui.dsl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.bluefw.blueui.dsl.render.widget.GridWidget;
import io.bluefw.blueui.dsl.render.widget.WidgetRender;
import io.bluefw.blueui.dsl.render.widget.WidgetRenderBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class Widget {
	private String id;
	private String binding;
	private String type;
	
	private int labelSpan;
	private int controlSpan;
	
	@JsonProperty("data-bind")  
	private String dataBind;
	
	private String label;
	private Map<String, Object> props = new HashMap<String, Object>();
	private Entity entity;
	
	public Widget(String binding) {
		this.binding = binding;
	}
	
	public String getLabel() {
		return StringUtil.isBlank(label) 
					? entity.getGlobalize(binding).value()
				    : label;
	}
	
	public String getId() {
		return StringUtil.isNotBlank(id) ? id : dataBind;
	}

	public StringBuffer render() {
		if (StringUtil.isBlank(dataBind)) {
			dataBind = binding;
		} 
		WidgetRender w = null;
		if (StringUtils.isBlank(type)) {
			w = WidgetRenderBuilder.build(this);
		} else if ("grid".equals(type)) {
			w = new GridWidget(this);
		}
		return w.render();
	}
}
